package com.baizw.cultivation.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baizw.cultivation.constant.CommonConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 网络相关工具类
 *
 * @author 剧终1204
 * @version V1.0
 * @date 2018年04月17日 10:12
 */
public class NetUtil extends cn.hutool.core.net.NetUtil {

    private static final Logger logger = LoggerFactory.getLogger(NetUtil.class);

    /**
     * 获取本机真实IP地址
     *
     * @return
     */
    public static Map<String, String> getRealIP() {
        //获取请求连接
        try {
            String ipJson = HttpUtil.get(CommonConstants.GET_IP_REAL);
            logger.info("获取结果: {}", ipJson);
            return JSONUtil.toBean(ipJson, Map.class);
        } catch (Exception e) {
            logger.error("获取本机真实IP地址失败!", e);
        }
        return new HashMap<>(0);
    }

    /**
     * 获取城市名称
     *
     * @return {@code city} 如果没有获取到 返回""
     */
    public static String getCity() {
        Map<String, String> result = getRealIP();
        String address = result.get("address");
        if (StrUtil.isNotBlank(address)) {
            int start = address.indexOf("\u7701");
            int end = address.indexOf("\u5e02");
            String city = address.substring(start + 1, end + 1);
            return city;
        }
        return "";
    }

    public static void main(String[] args) {
        System.out.println(getCity());
    }
}
